package com.java.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.common.model.Result;
import com.java.common.util.JwtUtil;
import com.java.manage.dao.MaintainMapper;
import com.java.manage.model.Maintain;
import com.java.manage.service.MaintainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MaintainServiceImpl implements MaintainService {

    @Autowired
    private MaintainMapper maintainMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result save(Maintain maintain) {
        maintainMapper.save(maintain);
        return Result.success();
    }

    @Override
    public Result modify(Maintain maintain) {
        maintainMapper.modify(maintain);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids) {
            maintainMapper.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result list(Maintain maintain) {
        PageHelper.startPage(maintain.getPageNum(), maintain.getPageSize());

        String token = request.getHeader("Token");
        Integer storeId = (Integer) JwtUtil.getClaims(token).get("storeId");
        maintain.setStoreId(storeId);

        List<Maintain> list = maintainMapper.list(maintain);
        PageInfo<Maintain> pageInfo = new PageInfo(list);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return Result.success(map);
    }

    @Override
    public Result get(int id) {
        Maintain maintain = maintainMapper.get(id);
        return Result.success(maintain);
    }

    @Override
    public Result getGenerate(List<Maintain> maintain) {
        Integer id = null;
        for (Maintain mai : maintain) {
            id = mai.getId();
        }
        Maintain maintain1 = maintainMapper.get(id);
        return Result.success(maintain1);
    }
}
